﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using CHGK.web.UI.Models;
using ChGK.Data;
using System.Web.Caching;

namespace CHGK.web.UI.Controllers
{
    public class AccountController : Controller
    {
        private DataManager _DataManager;
        private User TempUser;

        public AccountController()
        {
            _DataManager = new DataManager();
        }
        
        public AccountController(DataManager dataManager)
        {
            _DataManager = dataManager;
        }
        
        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            if (Request.IsAuthenticated)
            {
                if (_DataManager.Users.GetRoleByLogin(User.Identity.Name) == "User")
                {
                    return RedirectToAction("TeamPage", "Team", new {TourNumber = 1, QuestionNumber = 1});
                }
                else if (_DataManager.Users.GetRoleByLogin(User.Identity.Name) == "Superuser")
                {
                    return RedirectToAction("SuperuserPage", "Superuser");
                }
                else
                {
                    return RedirectToAction("LogOff", "Account");
                }
            }
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                //Проверяем нашего пользователя на залогиненность
                string sKey = model.UserName;
                string sUser = Convert.ToString(System.Web.HttpContext.Current.Cache[sKey]);
                //Если он ещё не залогинен
                if (sUser == null || sUser == String.Empty)
                {
                    //устанавливаем срок устаревания кеша
                    TimeSpan SessTimeOut = new TimeSpan(0, 0, System.Web.HttpContext.Current.Session.Timeout, 0, 0);
                    System.Web.HttpContext.Current.Cache.Insert(sKey, sKey, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null);
                    //Записываем в кеш сессии логин пользователя
                    Session["user"] = model.UserName;
                    //Пропускаем пользователя в систему
                    User _User = _DataManager.Users.GetUser(model.UserName);
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    //_DataManager.Users.UpdateUser(_User.Login, true);

                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else if (_User.Role == "User")
                    {
                        return RedirectToAction("TeamPage", "Team", new { TourNumber = 1, QuestionNumber = 1 });
                    }
                    else if (_User.Role == "Superuser")
                    {
                        return RedirectToAction("SuperuserPage", "Superuser");
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    //Кеш с таким пользователем существует, жаль...
                    ModelState.AddModelError("", "Данный пользователь уже вошёл в систему");
                }
              /* if (!_DataManager.Users.ValidateUser(model.UserName, model.Password).HasValue)
                {
                    ModelState.AddModelError("", "Данный пользователь уже вошёл в систему");
                }
                }
                else if (_DataManager.Users.ValidateUser(model.UserName, model.Password).Value == true)
                {
                    
                }
               */
               
            }
            else
            {
                ModelState.AddModelError("", "Логин или пароль введены неправильно");
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            string sKey = User.Identity.Name;
            //_DataManager.Users.UpdateUser(User.Identity.Name, false);
            System.Web.HttpContext.Current.Cache.Remove(sKey);             
            FormsAuthentication.SignOut();
            
            return RedirectToAction("LogOn", "Account");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register
        
        /*[HttpPost]
        public ActionResult RegisterUser(RegisterModel model)
        {
            
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                string UserLogin = null;
                UserLogin = _DataManager.Users.CreateUser(model.UserName, model.Password, "user");

                if (UserLogin != null)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    //!!!Сюда следует добавить реагирование на случай, если юзер при регистрации не создался
                    //ModelState.AddModelError("", ErrorCodeToString(createStatus));
                    return RedirectToAction("About", "Home");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }*/

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    TempUser = _DataManager.Users.GetUser(User.Identity.Name);
                    changePasswordSucceeded = _DataManager.Users.ChangePassword(TempUser.Login, model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
